﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAtletIS.Areas.Admin.Models;

namespace MvcAtletIS.Areas.Admin.Controllers
{
    public class ImagesController : Controller
    {
        private const string IMAGES_FOLDER_NAME = "~/Content/Articles/";
        
        public ActionResult Index(string ImageName)
        {
            List<ImageViewModel> model = new List<ImageViewModel>();
            
            var files = System.IO.Directory.GetFiles(Server.MapPath(IMAGES_FOLDER_NAME));
            if (files != null && files.Length > 0)
            {
                foreach (var item in files)
                {
                    var fileName = item.Substring(item.LastIndexOf('\\') + 1, item.Length - item.LastIndexOf('\\') - 1);
                    var image = new ImageViewModel { Name = fileName, Path = IMAGES_FOLDER_NAME + fileName };

                    if (string.IsNullOrEmpty(ImageName))
                    {
                        model.Add(image);
                    }
                    else
                    { 
                        if (fileName.ToLower().Contains(ImageName))
                            model.Add(image);
                    }
                    
                }
            }

            return View(model);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var fileName = System.IO.Path.GetFileName(file.FileName);
                var path = System.IO.Path.Combine(Server.MapPath(IMAGES_FOLDER_NAME), fileName);
                if (!System.IO.File.Exists(path))
                {
                    file.SaveAs(path);
                }
            }

            return RedirectToAction("Index");
        }

    }
}
